//
//  SaveCachesTool.m
//  jiulongLJ
//
//  Created by MyMac on 15/4/9.
//  Copyright (c) 2015年 MyMac. All rights reserved.
//

#import "SaveCachesTool.h"
#import "NSString+Hashing.h"
#import "FMDB.h"

#import <objc/runtime.h>
#import "Entity.h"

@interface SaveCachesTool()

@property(nonatomic,strong)NSManagedObjectModel*managerObjectModel;
@property(nonatomic,strong)NSPersistentStoreCoordinator*coordinator;
@property(nonatomic,strong)FMDatabaseQueue*queue;
@end
@implementation SaveCachesTool
+(SaveCachesTool*)shareSaveTool//单利
{
    
    
    static SaveCachesTool*tool;
    
    static dispatch_once_t onceToken ;
    dispatch_once(&onceToken, ^{
            tool = [[self alloc]init] ;
        
        }) ; 
    
    
    return tool;

    
}

+(BOOL)saveCachesPath:(NSString *)pathName andcachesData:(id)requestData
{
      NSString*str=   [self receicePath];
       NSString*path=[str stringByAppendingPathComponent:[pathName MD5Hash]];

    BOOL isSucceed=[requestData writeToFile:path atomically:YES];
    return isSucceed;
}
+(BOOL)fileExiste:(NSString*)pathName
{
     NSString*str=   [self receicePath];
    NSString*path=[str stringByAppendingPathComponent:[pathName MD5Hash]];
    
    return [[NSFileManager defaultManager]fileExistsAtPath:path];



}
+(NSData*)receiveCachesData:(NSString *)pathName
{
    NSString*str=   [self receicePath];

    NSString*path=[str stringByAppendingPathComponent:[pathName MD5Hash]];
    NSData*data=[NSData dataWithContentsOfFile:path];
   

        return data;

}
+(BOOL)removefile:(NSString *)pathName
{
    NSFileManager*manager=[NSFileManager defaultManager];
     NSString*str=   [self receicePath];

    NSString*path=[str stringByAppendingPathComponent:[pathName MD5Hash]];
    NSError*error=nil;
  BOOL ret=[manager removeItemAtPath:path error:&error];
    return ret;

}
+(NSString*)receicePath
{
    NSString*str=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSError*err=nil;
 [[NSFileManager defaultManager]createDirectoryAtPath:[str stringByAppendingPathComponent:@"Internet/file"] withIntermediateDirectories:YES attributes:nil error:&err];
    return [str stringByAppendingPathComponent:@"Internet/file"];
    
}
+(BOOL)removeAllFile
{
 NSFileManager*manager=[NSFileManager defaultManager];
 NSString*str=   [self receicePath];

    NSError*error=nil;
    BOOL ret=[manager removeItemAtPath:str error:&error];
  
    if(ret==NO)
    {
        NSLog(@"所有文件没有删除成功%@",error);
    }
    return ret;

}
-(NSManagedObjectContext*)context
{
    if(!_context){
        _context=[[NSManagedObjectContext alloc]init];
        [_context setPersistentStoreCoordinator:self.coordinator];
    }


    return _context;



}
/**
 *  NSManagedObjectModel管理所有实体与实体之间的联系，与coreData文件相关联
 *
 *  @return
 */
-(NSManagedObjectModel*)managerObjectModel
{
    if(!_managerObjectModel){
    
       NSURL*modelURL=[[NSBundle mainBundle]URLForResource:@"CoreDataModel" withExtension:@"momd"];
       _managerObjectModel=[[NSManagedObjectModel alloc]initWithContentsOfURL:modelURL];
    
    
    }


    return _managerObjectModel;


}
/**
 *  存储协调器，管理了存储形式，，，是sqlite数据库还是xml文件，抑或其他方式,还关联了NSManagedObjectModel文件
 *
 *  @return
 */
-(NSPersistentStoreCoordinator *)coordinator
{

    if(!_coordinator){
       
        NSString*docment=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        NSString*sqlite=[docment stringByAppendingPathComponent:@"coreData.sqlite"];
        //关联了NSManagedObjectModel
        _coordinator=[[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:self.managerObjectModel];
        NSError*error;
        //设置了底层存储形式，此处为数据库形式，
        //至于已经有了coreData的NSManagedObjectModel的文件，，为什么还需要创建sqlite文件，这里可以这样理解，NSManagedObjectModel实际是在sqlite的文件基层封装的，NSManagedObjectModel的内部映射了sqlite的数据，操作NSManagedObjectModel实际还是在操作sqlite文件
  NSPersistentStore*persistentStore=[_coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlite] options:nil error:&error];
        if(persistentStore==nil){
        
            NSLog(@"设置持久化存储类型失败：%@\n%@",error,[error userInfo]);
        
        }
    
    
    }
    return _coordinator;





}

+(void)saveCoreData:(id)object andClass:(Class)objcClass
{
    if ([NSStringFromClass([[object class]superclass])isEqualToString:@"NSManagedObject"]) {
        NSLog(@"object传入一个非继承NSManagedObject的对象，或者字典");
        return;
    }
    
    
    SaveCachesTool*tool=[SaveCachesTool shareSaveTool];
    
    id objc=[NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass(objcClass) inManagedObjectContext:tool.context];
    if([object isKindOfClass:[NSDictionary class]]){
  
      [objc setValuesForKeysWithDictionary:object];
    }else{
  
        NSMutableArray*propertyName=[tool receivePropertyNameObjc:object];
            for (NSInteger i=0; i<propertyName.count; i++) {
                NSString*name=propertyName[i];
               id value=[object valueForKey:name];
                if(value==nil){
                
                value=@"";
                }
                [objc setValue:value forKey:name];
            }
        
    
  
    }
    
    NSError*error=nil;
    if([tool.context save:&error]){
    
        NSLog(@"coreData保存成功");
    
    }else{
        NSLog(@"coreData保存失败：%@",error);
    
    }



}

+(void)deletedCoreData:(id)object andClass:(Class)objeClass
{
     SaveCachesTool*tool=[SaveCachesTool shareSaveTool];
    //id objc=[NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass(objeClass) inManagedObjectContext:tool.context];
    
    if([object isKindOfClass:[NSDictionary class]]){
  NSArray*ret=[self dictSearch:object andClass:objeClass];
    //[objc setValuesForKeysWithDictionary:object];
        for (NSInteger i=0; i<ret.count; i++) {
            id objc=ret[i];
            [tool.context deleteObject:objc];
        }
  
    }else{
        if([NSStringFromClass([[object class]superclass])isEqualToString:@"NSManagedObject"]){
            [tool.context deleteObject:object];
        
        }else{
            NSDictionary*dict=[tool modelToDict:object];
            NSArray*ret=[self dictSearch:dict andClass:objeClass];
            //[objc setValuesForKeysWithDictionary:object];
            for (NSInteger i=0; i<ret.count; i++) {
                id objc=ret[i];
                [tool.context deleteObject:objc];
            }
            
            
            
        }
}
    
    
    NSError*error=nil;
    if([tool.context save:&error]){
    
    
        NSLog(@"CoreData删除实体成功");
    
    }else{
        NSLog(@"CoreData删除实体失败:%@",error);
    
    }



}
+(NSArray*)searchCoreDataClass:(Class)objcClass andPredicateString:(NSPredicate*)predicateStr
{
    SaveCachesTool*tool=[SaveCachesTool shareSaveTool];
    NSFetchRequest*request=[[NSFetchRequest alloc]init];
    //设置抓取哪种实体
    NSEntityDescription*entity=[NSEntityDescription entityForName:NSStringFromClass(objcClass) inManagedObjectContext:tool.context];
    request.entity=entity;
    request.predicate=predicateStr;
    NSError*error=nil;
    NSArray*array=[tool.context executeFetchRequest:request error:&error];
    return array;
    

}

+(void)updataCoreDataFromEntity:(id)fromObject toEntity:(id)toObject andEntityClass:(Class)entityClass
{
        if ([NSStringFromClass([[fromObject class]superclass])isEqualToString:@"NSManagedObject"]||[NSStringFromClass([[toObject class]superclass])isEqualToString:@"NSManagedObject"]) {
        NSLog(@"object传入一个非继承NSManagedObject的对象，或者字典");
        return;
    }
    
    SaveCachesTool*tool=[SaveCachesTool shareSaveTool];
    if([fromObject isKindOfClass:[NSDictionary class]]&&[toObject   isKindOfClass:[NSDictionary class]]){
        [self updata:fromObject and:toObject and:entityClass];
        
        
     }else{
        NSDictionary*oldDict=[tool modelToDict:fromObject];
        NSDictionary*newDict=[tool modelToDict:toObject];
        [self updata:oldDict and:newDict and:entityClass];
    
    }
    NSError*error=nil;
    if([tool.context save:&error]){
        NSLog(@"coreData更新成功");
    }else{
        NSLog(@"coreData更新失败:%@",error);
    
    }




}

+(void)updata:(NSDictionary*)fromObject and:(NSDictionary*)toObject and:(Class)entityClass
{
    
    NSArray*entityArray=[self dictSearch:fromObject andClass:entityClass];
    NSArray*keyArray=fromObject.allKeys;
    for (NSInteger i=0; i<entityArray.count; i++) {
        id old=entityArray[i];
        for (NSInteger j=0; j<keyArray.count; j++) {
            [old setValue:toObject[keyArray[j]] forKey:keyArray[j]];
        }
        
    }



}
+(NSArray*)dictSearch:(NSDictionary*)dict andClass:(Class)entityClass
{
    NSMutableString*searchStr=[[NSMutableString alloc]init];
    NSMutableArray*valueArray=[NSMutableArray array];
    NSMutableArray*keyArray=[NSMutableArray array];
    NSDictionary*from=dict;
    for (NSInteger i=0; i<from.allKeys.count; i++) {
        NSString*key=from.allKeys[i];
        NSString*value=from[key];
        [valueArray addObject:value];
        [keyArray addObject:key];
        if(i!=from.allKeys.count-1){
            [searchStr appendFormat:@"%@=%@&&",key,@"%@"];
        }else{
            
            [searchStr appendFormat:@"%@=%@",key,@"%@"];
            
        }
        
    }
    //[NSPredicate predicateWithFormat:searchStr argumentArray:valueArray]前面是参数，后面是值
    NSArray*entityArray= [self searchCoreDataClass:entityClass andPredicateString:[NSPredicate predicateWithFormat:searchStr argumentArray:valueArray]];

    return entityArray;



}

//@"create table if not exists Content_Model (id integer primary key autoincrement, Id text,Title text,AbstractContent text,ContentType text, StoreNum text,TitleImage text,IsRecommend text,IsTop text,PraiseNum text,TeacherPraiseNum text,ViewNum text,PlayTime text,SetNo text,ReleaseTime text,LabelList text,Label text,LabelId text,LabelName text);"
+(BOOL)createTabelSqliteLanguage:(NSString*)language andpath:(NSString*)pathName//创表
{
    SaveCachesTool*tool=[SaveCachesTool shareSaveTool];
    NSString*str=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString*filename=[str stringByAppendingPathComponent:pathName];
    NSLog(@"表＊＊＊＊%@",filename);
    // 1.创建数据库队列
    if([[NSFileManager defaultManager]fileExistsAtPath:filename]==NO||tool.queue==nil){
        tool.queue = [FMDatabaseQueue databaseQueueWithPath:filename];
    }

   // 2.创表
     __block BOOL result;
    [tool.queue inDatabase:^(FMDatabase *db) {
        
        result= [db executeUpdate:language];
        
        if (result) {
            NSLog(@"创表成功");
        } else {
            NSLog(@"创表失败");
        }
    }];

   return result;

}

//@"insert into t_student (name, age) values (?, ?);"
//[db executeUpdate:@"insert into namedparamcounttest values (:a, :b, :c, :d)" withParameterDictionary:dictionaryArgs]
//[db executeUpdate:@"DROP TABLE User"]
//@"ALTER TABLE Teachers ADD COLUMN name text";
+(BOOL)insertdataSqliteLanguage:(NSString*)language and:(NSDictionary*)dict//增
{
     SaveCachesTool*tool=[SaveCachesTool shareSaveTool];

    __block BOOL result;
    [tool.queue inDatabase:^(FMDatabase *db) {
        if(dict==nil){
        result=[db executeUpdate:language];
        }else{
            //此方法创表时不能有主键
        result =[db executeUpdate:language withParameterDictionary:dict];//根据字典存储数据
   }
    }];
    return  result;
    
}
//@"delete from t_student where ID=?"
+(BOOL)deleteDataSqliteLanguage:(NSString*)language//删
{
    SaveCachesTool*tool=[SaveCachesTool shareSaveTool];
    __block BOOL result;
    [tool.queue inDatabase:^(FMDatabase *db) {
      result=  [db executeUpdate:language];
        
    }];
    return result;
}
//@"update t_student set age = ? where name = ?;"
+(BOOL)updataDataSqliteLanguage:(NSString*)language//改
{
    SaveCachesTool*tool=[SaveCachesTool shareSaveTool];
    __block BOOL result;
    [tool.queue inDatabase:^(FMDatabase *db) {
     result=[db executeUpdate:language];

    }];

    return  result;
}
//@"select * from t_student where age > ?;"
+(NSArray*)searchDataSqliteLanguage:(NSString*)language
{
    SaveCachesTool*tool=[SaveCachesTool shareSaveTool];
    NSMutableArray*array=[[NSMutableArray alloc]init];
    [tool.queue inDatabase:^(FMDatabase *db) {
        FMResultSet *rs = [db executeQuery:language];
        while (rs.next) {
        NSDictionary*dict=[rs resultDictionary];
            [array addObject:dict];
        }
    }];
    return  array;
}
+(NSString*)libraryPath:(NSString*)name;
{
    NSString*str=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString*filename=[str stringByAppendingPathComponent:name];

    return filename;


}
//获取对象的所有属性名
-(NSMutableArray*)receivePropertyNameObjc:(id)object
{
    NSMutableArray*nameArray=[[NSMutableArray alloc]init];
    unsigned int count=0;
  objc_property_t*propertys=class_copyPropertyList(object_getClass(object), &count);
    for (int i=0; i<count; i++) {
        objc_property_t property=propertys[i];
      const  char*propertyName=property_getName(property);
        NSString*name=[NSString stringWithUTF8String:propertyName];
        [nameArray addObject:name];
    }
    free(propertys);


    return nameArray;

}
-(NSDictionary*)modelToDict:(id)object
{
    NSMutableDictionary*dict=[NSMutableDictionary dictionary];
    NSMutableArray*array=[self receivePropertyNameObjc:object];
    for (NSInteger i=0; i<array.count; i++) {
        //NSLog(@"%@",array[i]);
        id value=[object valueForKey:array[i]];
        if(value==nil){
            NSLog(@"值为nil");
        value=@"";
        }
        [dict setObject:value forKey:array[i]];
    }
    return dict;





}
-(void)dealloc
{

    NSLog(@"缓存%@",self.class);

}
@end
